package cc.rico.tutorial.sync;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by rico on 2018/8/19.
 */
public class ClientApp {
    private static final Logger logger = LoggerFactory.getLogger(ClientApp.class);
    private FtpConfig ftpConfig;


    public void run() throws InterruptedException {
        this.getFtpConfig();
        this.upload();
        this.download();
    }

    public void upload() throws InterruptedException {
        Thread.sleep(1000*2);
        logger.info("##upload[ftpConfig={}]", ftpConfig);
    }

    public void download() throws InterruptedException {
        Thread.sleep(1000*2);
        logger.info("##download[ftpConfig={}]", ftpConfig);
    }

    private FtpConfig getFtpConfig() {
        if(ftpConfig == null) {
            ZkClient zkClient = new ZkClient("192.168.223.140:2181");
            ftpConfig = zkClient.readData(ConfigManager.CONFIG_PATH);
            logger.info("##ClientApp.getFtpConfig[ftpConfig={}]", ftpConfig);

            zkClient.subscribeDataChanges(ConfigManager.CONFIG_PATH, new IZkDataListener() {
                @Override
                public void handleDataChange(String dataPath, Object data) throws Exception {
                    logger.info("##handleDataChange.dataPath={}", dataPath);
                    logger.info("##handleDataChange.data={}", data);
                    ftpConfig = (FtpConfig) data;
                }

                @Override
                public void handleDataDeleted(String dataPath) throws Exception {
                    logger.info("##handleDataDeleted.dataPath={}", dataPath);
                    ftpConfig = null;
                }
            });
        }

        return ftpConfig;
    }

}
